<template>
  <div class="mod-prod prod-list-mod">
    <avue-crud
      ref="crud"
      :page="page"
      :data="dataList"
      :table-loading="dataListLoading"
      @on-load="getDataList"
      @sort-change="sortChange"
      @search-reset="searchReset"
      :option="tableOption"
      @search-change="searchChange"
      @refresh-change="refreshChange"
      @selection-change="handleSelectionChange"
    >
      <template slot-scope="scope" slot="deliveryMode">
        <div>{{scope.row.deliveryMode | DeliveryMode}}</div>
      </template>
      <!-- 0:商家下架 1:正常 2:平台下架 3:待平台审核 4:审核失败 -1表示删除 -->
      <template slot-scope="scope" slot="status">
        <el-tag v-if="scope.row.status === 1" type="success" size="small">{{
          $t("publics.UpperShelf")
        }}</el-tag>
        <el-tag v-else-if="scope.row.status === 0" size="small">{{
          $t("publics.metLowerShelf")
        }}</el-tag>
        <el-tag v-else-if="scope.row.status === 2" size="small" type="danger">{{
          $t("product.violatingGoods")
        }}</el-tag>
        <el-tag
          v-else-if="scope.row.status === 3"
          type="warning"
          size="small"
          >{{ $t("product.pendingReview") }}</el-tag
        >
        <el-tag v-else-if="scope.row.status === 4" type="danger" size="small">{{
          $t("product.refuseToPass")
        }}</el-tag>
        <el-tag v-else size="small">{{ $t("product.other") }}</el-tag>
      </template>
      <template slot="search">
        <el-col :md="6" :xs="24">
          <el-form-item :label="this.$i18n.t('product.prodName')">
            <el-input
              v-model="prodName"
              :placeholder="this.$i18n.t('product.prodName')"
              maxlength="30"
              clearable
              show-word-limit
            ></el-input>
          </el-form-item>
        </el-col>
      </template>
      <template slot-scope="scope" slot="isTop">
        <el-tag v-if="scope.row.isTop === 0" size="small">{{$t('publics.no')}}</el-tag>
        <el-tag
          v-else-if="scope.row.isTop === 1"
          size="small"
          type="success"
        >{{$t('publics.yes')}}</el-tag>
      </template>
      <template slot-scope="scope" slot="isCompose">
        <el-tag v-if="scope.row.isCompose === 1" type="success" size="small">{{
            $t("product.comProd")
          }}</el-tag>
        <el-tag v-else size="small">{{ $t("product.ordProd") }}</el-tag>
      </template>
      <template slot-scope="scope" slot="status">
        <el-tag v-if="scope.row.status === 1" type="success" size="small">{{
            $t("publics.UpperShelf")
          }}</el-tag>
        <el-tag v-else size="small">{{ $t("publics.LowerShelf") }}</el-tag>
      </template>
      <template slot="menuLeft">
        <el-button
          class="operation-btn"
          @click="getExportExcel()"
          size="medium"
          type="primary"
          icon="el-icon-document-checked"
          v-if="isAuth('prod:prod:exportProd')"
          >{{ $t("formData.export") }}</el-button
        >
        <el-button
          icon="el-icon-bottom"
          size="medium"
          type="primary"
          @click.stop="getUpload()"
          v-if="isAuth('prod:prod:downloadModel')"
          >{{ $t("product.importGoods") }}</el-button
        >
        <br>
        <el-button
          type="success"
          @click="batchChangeProdStatus(1)"
          size="small"
          v-if="isAuth('prod:prod:batchStatus')"
          :disabled="dataListSelections.length <= 1"
        >{{ $t("product.batchUp") }}</el-button>
        <el-button
          type="primary"
          @click="batchChangeProdStatus(0)"
          size="small"
          v-if="isAuth('prod:prod:batchStatus')"
          :disabled="dataListSelections.length <= 1"
        >{{ $t("product.batchDown") }}</el-button>
        <el-button
          type="danger"
          @click="batchDeleteHandle()"
          size="small"
          v-if="isAuth('prod:prod:batchDelete')"
          :disabled="dataListSelections.length <= 1"
        >{{$t('sys.batchDelete')}}</el-button>
      </template>
      <template slot-scope="scope" slot="menu">
        <div class="menu-btn">
          <el-button
            v-if="isAuth('prod:prod:update')"
            type="primary"
            icon="el-icon-edit"
            size="small"
            class="operate-btn"
            @click="addOrUpdateHandle(scope.row.prodId)"
            >{{ $t("crud.updateBtn") }}</el-button
          >
          <el-button
            type="primary"
            icon="el-icon-top"
            size="small"
            class="operate-btn"
            v-if="isAuth('prod:prod:status') && scope.row.status === 0"
            @click="changeProdStatus(scope.row.prodId, 1)"
            >{{ $t("publics.UpperShelf") }}</el-button
          >
          <el-button
            type="primary"
            icon="el-icon-bottom"
            size="small"
            class="operate-btn"
            v-if="isAuth('prod:prod:status') && scope.row.status === 1"
            @click="changeProdStatus(scope.row.prodId, 0)"
            >{{ $t("publics.LowerShelf") }}</el-button
          >
          <el-button
            type="primary"
            size="small"
            icon="el-icon-document-checked"
            v-if="isAuth('prod:prod:audit') && scope.row.status > 1"
            @click="applyAuditHandle(scope.row.prodId)"
            >{{ $t("product.offlineManagement") }}</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="small"
            class="operate-btn"
            v-if="isAuth('prod:prod:delete')"
            @click="deleteHandle(scope.row.prodId)"
            >{{ $t("text.delBtn") }}</el-button
          >
        </div>
      </template>
    </avue-crud>
    <!-- 下线管理弹窗-->
    <ProdOfflineHandleEvent
      v-if="prodOfflineHandleEventVisible"
      selectUrl="/prod/prod/getOfflineHandleEventByProdId"
      applyUrl="/prod/prod/auditApply"
      ref="prodOfflineHandleEvent"
      @refreshDataList="refreshChange"
    ></ProdOfflineHandleEvent>
    <prod-upload
      v-if="uploadVisible"
      ref="prodUpload"
      @refreshDataList="getWaitingConsignmentExcel"
    ></prod-upload>
  </div>
</template>

<script>
import { tableOption } from '@/crud/prod/prodList'
import ProdUpload from './prod-upload'
import ProdOfflineHandleEvent from '@/components/offline-event-handle'
import i18n from '../../../i18n/i18n'
export default {
  data () {
    return {
      dataForm: {
        prodName: ''
      },
      dataList: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10 // 每页显示多少条
      },
      searchForm: {},
      prodName: '',
      prodNameRouter: '',
      dataListSelections: [],
      // 0无 1.排序号排序
      sortParam: 0,
      // 0无 1 正序 2倒序
      sortType: 0,
      dataListLoading: false,
      uploadVisible: false,
      prodOfflineHandleEventVisible: false,
      tableOption: tableOption,
      resourcesUrl: window.SITE_CONFIG.resourcesUrl
    }
  },
  components: {
    ProdOfflineHandleEvent,
    ProdUpload
  },
  created () {
    if (this.$route.query.prodName) {
      this.prodNameRouter = this.$route.query.prodName
    }
  },
  filters: {
    DeliveryMode: function (value) {
      // 将商品的配送方式字符串转化为json
      let objValue = JSON.parse(value)
      // 声明返回结果 result
      let result = []
      if (objValue.hasCityDelivery === true) {
        result.push(i18n.t('product.sameCityDelivery'))
      }
      if (objValue.hasUserPickUp === true) {
        result.push(i18n.t('product.userPickUp'))
      }
      if (objValue.hasShopDelivery === true) {
        result.push(i18n.t('product.shopDelivery'))
      }
      return result.join(' / ')
    }
  },
  methods: {
    // 获取数据列表
    getDataList (page) {
      if (this.page) {
        let size = Math.ceil(this.page.total / this.page.pageSize)
        this.page.currentPage = this.page.currentPage > size ? size : this.page.currentPage
      }
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/prod/prod/page'),
        method: 'get',
        params: this.$http.adornParams(
          Object.assign(
            {
              current: page == null ? this.page.currentPage : page.currentPage,
              prodName: this.prodNameRouter ? this.prodNameRouter : this.prodName,
              size: page == null ? this.page.pageSize : page.pageSize,
              sortParam: this.sortParam,
              sortType: this.sortType
            },
            this.searchForm
          )
        )
      }).then(({ data }) => {
        this.dataList = data.records
        console.log(this.dataList)
        for (const key in this.dataList) {
          if (this.dataList.hasOwnProperty(key)) {
            const element = this.dataList[key]
            if (element.imgs != null && element.imgs !== '') {
              element.imgs = element.imgs.split(',')[0]
            }
          }
        }
        this.page.total = data.total
        this.page.currentPage = data.current
        this.dataListLoading = false
        this.prodNameRouter = null
      })
    },
    // 新增 / 修改
    addOrUpdateHandle (id) {
      this.$router.push({
        path: '/prodInfo',
        query: { prodId: id }
      })
    },
    // 刷新数据
    getWaitingConsignmentExcel () {
      this.getDataList(this.page)
    },
    // 删除
    deleteHandle (id) {
      var ids = id ? [id] : this.dataListSelections.map(item => {
        return item.prodId
      })
      this.$confirm(`${this.$i18n.t('admin.isDeleOper')}?`, this.$i18n.t('text.tips'), {
        confirmButtonText: this.$i18n.t('crud.filter.submitBtn'),
        cancelButtonText: this.$i18n.t('crud.filter.cancelBtn'),
        type: 'warning'
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl(`/prod/prod/${id}`),
            method: 'delete',
            data: this.$http.adornData({})
          }).then(({ data }) => {
            this.page.total = this.page.total - ids.length
            this.$message({
              message: this.$i18n.t('publics.operation'),
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList(this.page)
              }
            })
          })
        })
        .catch(() => { })
    },
    // 多选变化
    handleSelectionChange (val) {
      this.dataListSelections = val
    },
    // 批量改变状态
    batchChangeProdStatus (status) {
      var prodList = this.dataListSelections.filter(item => {
        if (status === 0 && item.status === 1) {
          // 进行下架商品操作，则只改变状态为上架的
          return true
        } else if (status === 1 && item.status === 0) {
          // 进行上架商品操作，则只改变状态为下架的
          return true
        } else {
          // 其他状态不做修改
          return false
        }
      })
      var ids = prodList.map(item => {
        return item.prodId
      })
      this.$confirm(`${this.$i18n.t('sys.makeSure')}【${status ? this.$i18n.t('product.batchUp') : this.$i18n.t('product.batchDown')}】${this.$i18n.t('publics.operating')}?`, this.$i18n.t('text.tips'), {
        confirmButtonText: this.$i18n.t('crud.filter.submitBtn'),
        cancelButtonText: this.$i18n.t('crud.filter.cancelBtn'),
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/prod/prod/batchProdStatus/' + status),
          method: 'put',
          data: this.$http.adornData(ids, false)
        }).then(({ data }) => {
          this.$message({
            message: this.$i18n.t('publics.operation'),
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.refreshChange()
            }
          })
        })
      }).catch(() => { })
    },
    // 批量删除
    batchDeleteHandle () {
      var ids = this.dataListSelections.map(item => {
        return item.prodId
      })
      this.$confirm(`${this.$i18n.t('sys.makeSure')}【${this.$i18n.t('sys.batchDelete')}】${this.$i18n.t('publics.operating')}?`, this.$i18n.t('text.tips'), {
        confirmButtonText: this.$i18n.t('crud.filter.submitBtn'),
        cancelButtonText: this.$i18n.t('crud.filter.cancelBtn'),
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/prod/prod'),
          method: 'delete',
          // data: this.$http.adornData({})
          data: this.$http.adornData(ids, false)
        }).then(({ data }) => {
          this.$message({
            message: this.$i18n.t('publics.operation'),
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.refreshChange()
            }
          })
        })
      }).catch(() => { })
    },
    changeProdStatus (id, status) {
      this.$confirm(`${this.$i18n.t('sys.makeSure')}【${status ? this.$i18n.t('publics.UpperShelf') : this.$i18n.t('publics.LowerShelf')}】${this.$i18n.t('text.menu')}?`, this.$i18n.t('text.tips'), {
        confirmButtonText: this.$i18n.t('crud.filter.submitBtn'),
        cancelButtonText: this.$i18n.t('crud.filter.cancelBtn'),
        type: 'warning'
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl(`/prod/prod/prodStatus`),
            method: 'put',
            data: this.$http.adornData({
              status: status,
              prodId: id
            })
          }).then(({ data }) => {
            this.$message({
              message: this.$i18n.t('publics.operation'),
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.page.currentPage = 1
                this.getDataList(this.page)
              }
            })
          })
        })
    },
    // 条件查询
    searchChange (params) {
      this.searchForm = params
      this.page.currentPage = 1
      this.getDataList(this.page)
    },
    // 跳转至导入选择
    getUpload () {
      this.uploadVisible = true
      this.$nextTick(() => {
        this.$refs.prodUpload.init()
      })
    },
    getExportExcel () {
      this.$confirm(`${this.$i18n.t('product.reportsToCond')}`, this.$i18n.t('text.tips'), {
        confirmButtonText: this.$i18n.t('crud.filter.submitBtn'),
        cancelButtonText: this.$i18n.t('crud.filter.cancelBtn'),
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/prod/prod/exportProd'),
          method: 'get',
          params: this.$http.adornParams(this.searchForm),
          responseType: 'blob' // 解决文件下载乱码问题
        }).then(({ data }) => {
          var blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
          const fileName = this.$i18n.t('product.comInfoSorXls')
          const elink = document.createElement('a')
          if ('download' in elink) { // 非IE下载
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href) // 释放URL 对象
            document.body.removeChild(elink)
          } else { // IE10+下载
            navigator.msSaveBlob(blob, fileName)
          }
        })
      })
    },
    // 申请审核
    applyAuditHandle (id) {
      this.prodOfflineHandleEventVisible = true
      this.$nextTick(() => {
        this.$refs.prodOfflineHandleEvent.init(id)
      })
    },
    toTopHandle (row) {
      var str = this.$i18n.t('publics.isTop')
      if (row.roomTop) {
        str = this.$i18n.t('liveRoom.cancelTopping')
      }
      this.$confirm(this.$i18n.t('remindPop.makeSure') + ' ' + str + ' ' + this.$i18n.t('remindPop.operation') + '?', this.$i18n.t('remindPop.remind'), {
        confirmButtonText: this.$i18n.t('remindPop.confirm'),
        cancelButtonText: this.$i18n.t('remindPop.cancel'),
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/prod/prod/toTop/' + row.prodId),
          method: 'put',
          data: this.$http.adornData({})
        }).then(({ data }) => {
          this.$message({
            message: this.$i18n.t('remindPop.succeeded'),
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.refreshChange()
            }
          })
        })
      }).catch(() => { })
    },
    sortChange (data) {
      console.log(data)
      // 排序字段 0无 1加入时间 2累计客户 3累计邀请 4累计收益
      switch (data.prop) {
        case 'seq': this.sortParam = 1
          break
      }
      // 排序类型 0无 1 正序 2倒序
      switch (data.order) {
        case 'descending': this.sortType = 2
          break
        case 'ascending': this.sortType = 1
          break
        default: this.sortType = 0
          break
      }
      this.getDataList(this.page)
    },
    // 清空自定义数据
    searchReset () {
      this.prodName = ''
    },
    // 回调刷新
    refreshChange () {
      this.page = this.$refs.crud.$refs.tablePage.defaultPage
      this.getDataList()
    }
  }
}
</script>

<style  lang="scss">
.mod-prod.prod-list-mod {
  .operate-btn {
    margin-left: 5px !important;
  }
  .operate-btn:first-child {
    margin-left: 0 !important;
  }
  .menu-btn {
    .el-button.el-button--primary.el-button--small,
    .el-button.el-button--danger.el-button--small {
      margin-bottom: 8px;
    }
  }
}

</style>
<style scoped>
/deep/ .el-input--suffix .el-input__inner {
  padding-right: 65px;
}
</style>
